import { reqCode, reqLogin, reqLogout, reqUserInfo, reqUserRegister } from "@/api"
// 引入封装的cookies函数
import { setCookie, getCookie, delCookie } from '@/utils/cookie'

// 用户登陆、注册模块
export default {
  actions: {
    // 获取验证码
    async getCode ({ commit }, phone) {
      const result = await reqCode(phone);
      if (result.code == 200) {
        commit('GETCODE', result.data);
      } else {
        return Promise.reject(new Error('请求验证码失败!'));
      }
    },

    // 用户注册
    async userRegister ({ commit }, user) {
      let result = await reqUserRegister(user);
      // console.log(result);
      if (result.code == 200) {
        return '注册成功!'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    // 用户登陆
    async userLogin ({ commit }, user) {
      let result = await reqLogin(user)
      if (result.code == 200) {
        // 将令牌存储在cookie中
        setCookie('token', result.data.token, 3600 * 24);
        commit('USERLOGIN', result.data.token);
        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },

    // 获取用户登陆信息
    async getUserInfo ({ commit }) {
      let result = await reqUserInfo();
      if (result.code == 200) {
        commit('GETUSERINFO', result.data);
        return '获取成功'
      } else {
        return Promise.reject(new Error('获取失败'))
      }
    },

    // 退出登录
    async logout ({ commit }) {
      let result = await reqLogout()
      if (result.code == 200) {
        commit('CLEARTOKEN');
        return result.message;
      } else {
        return Promise.reject(result.message)
      }
    }
  },
  mutations: {
    // 获取验证码
    GETCODE (state, code) {
      state.code = code;
    },

    // 获取用户登陆返回的token
    USERLOGIN (state, token) {
      state.token = token;
    },

    // 获取用户登陆信息
    GETUSERINFO (state, userLoginData) {
      state.userLoginData = userLoginData;
    },

    // 清除存在vuex中的token和userLoginData
    CLEARTOKEN (state) {
      state.token = '';
      state.userLoginData = {};
    }
  },
  state: {
    code: '',
    // 优先获取cookie里的token，如果不存在，说明用户没有登陆，token为‘ ’
    token: getCookie('token') || '',
    userLoginData: {}
  },
  getters: {
    name: state => {
      return state.userLoginData.name
    }
  }
}
